<template>
	<view class="content">
		<view class="field">
			<u-field
				v-model="code"
				label="验证码"
				placeholder="请填写验证码"
				:border-bottom="false"
			>
				<view class="pwd" slot="right" @click="getcode">
					{{codeText}}
				</view>
			</u-field>
			<u-field
				maxlength="6"
				type="password"
				class="linput"
				v-model="pwd"
				label="设置密码"
				placeholder="请设置登录密码"
				:border-bottom="false"
			>
			</u-field>
		</view>
		<button class="new-btn" @click="submit">立即修改</button>
		<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
	</view>
</template>

<script>
	export default {
		data () {
			return {
				codeText: '发送验证码',
				phone: '',
				code: '',
				pwd: '',
				yzPhone: '',
				yzCode: ''
			}
		},
		onLoad() {
			this.$store.dispatch('getuserinfo').then(res=>{
				if(res.phone){
					this.phone = res.phone
				}else{
					uni.navigateTo({
						url:'/pages/phone/index'
					})
				}
			})
		},
		methods:{
			async submit(){
				if (!this.code || this.code != this.yzCode || this.phone != this.yzPhone) {
					this.$u.toast('验证码不正确');
					return;
				}
				if(this.pwd.length == 6 && this.pwd.length == String(parseInt(this.pwd)).length){
					const {data:res} = await this.$Request({
						url:'api/user/editInfo',
						data:{
							user_id: this.$store.state.userid,
							paypwd: this.pwd
						}
					})
					if (res && res.code == 200) {
						this.code = ''
						this.yzCode = ''
						this.$u.toast('修改密码成功');
					} else {
						this.$u.toast('密码修改失败');
					}
				}else{
					this.$u.toast('密码格式为6位数字')
				}
			},
			codeChange(text) {
				this.codeText = text;
			},
			async getcode() {
				if(this.$refs.uCode.canGetCode) {
					var code = Math.floor(Math.random() * (999999 - 100000 + 1) + 100000);
					const {
						data: res
					} = await this.$Request({
						url: 'api/code/sms',
						data: {
							phone: this.phone,
							code: code
						}
					})

					this.$u.toast(res.msg);
					if (res && res.code == 200) {
						this.yzPhone = this.phone;
						this.yzCode = code;
						this.$refs.uCode.start();
					}
				}else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.content{
		/* #ifndef H5 */
		min-height: 100vh;
		/* #endif */
		/* #ifdef H5 */
		min-height: calc(100vh - 44px);
		/* #endif */
		background-color: #2A2931;
		overflow: hidden;
		.field{
			margin: 60rpx 30rpx;
			.pwd{
				color: #A87B38;
			}
			/deep/.u-field{
				padding: 14px 20px;
				display: flex;
				align-items: center;
				position: relative;
				border-radius: 60px;
				margin-bottom: 30rpx;
				background: rgba(153, 149, 149, 0.466);
				.u-label-text{
					color: #A87B38;
				}
				input{
					color: #eee;
				}
			}
		}
	}
</style>
